<template>
  <div class="modal-from">
    <a-modal
      title="客户登记"
      :width="720"
      style="top: 50px;"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="submit"
      @cancel="handleCancel"
    >
      <a-row :gutter="24">
        <a-col :md="12" :sm="24" >
          <a-form :form="form" layout="vertical"  class="input-search">
            <a-form-item label="联系号码" :wrapperCol="wrapperCol" has-feedback>
              <a-input-search
                :loading="searchInputLoading"
                @search="searchCustomer"
                enter-button
                :maxLength="11"
                :minLength="11"
                ref="phoneInput"
                style="width: 100%"
                placeholder="请输入联系号码"
                v-decorator="['customerContact.contactContent',{rules: [{ required: true, message: '请输入联系号码！'},{validator: phoneCheck.bind(this)}]}]" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="联系方式"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select allow-clear style="width: 100%" v-decorator="['customerContact.contactType', {rules: [{ required: true, message: '请选择联系方式！' }]}]"  placeholder="请选择联系方式" >
                <a-select-option v-for="(item,index) in CustomerConsult.contactDetails"  :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="客户姓名"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                :disabled="true"
                ref="nameInput"
                placeholder="请输入客户姓名"
                style="width: 100%"
                v-decorator="['customer.name',{rules: [{ required: true, message: '请输入客户姓名！' }]}]" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="性别"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select
                :disabled="true"
                allow-clear
                style="width: 100%"
                placeholder="请选择性别"
                v-decorator="['customer.sex', {rules: [{ required: true, message: '请选择性别！' }]}]" >
                <a-select-option  v-for="(item,index) in sex" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="年龄"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                :disabled="true"
                ref="ageInput"
                placeholder="请输入客户年龄"
                style="width: 100%"
                v-decorator="['customer.age',{rules: [{ required: false, message: '请输入客户年龄！' }]}]" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form" layout="vertical">
            <a-form-item label="科室" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                :showSearch="true"
                option-filter-prop="children"
                allow-clear
                option-label-prop="label"
                style="width: 100%"
                v-decorator="['execDept', {rules: [{ required: true, message: '请先选择科室！' }]}]"
                placeholder="请选择科室">
                <a-select-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <!-- <a-col :md="12" :sm="24">
          <a-form class="radio-group" :form="form" layout="vertical">
            <a-form-item label="是否复查" has-feedback labelAlign="left">
              <a-radio-group  v-decorator="['isReview', {rules: [{ required: true, message: '请选择！' }]}]" >
                <a-radio :value="1">是</a-radio>
                <a-radio :value="0">否</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-col> -->
      </a-row>

      <!--用户模块弹出窗，待优化抽离-->
      <a-modal
        :footer="null"
        title="双击选择客户"
        :width="800"
        :visible="visibleTable"
        :confirmLoading="confirmLoading"
        @ok="handleSubmit"
        @cancel="visibleTable=false"
      >
        <a-table
          :alert="true"
          :columns="columns"
          :data-source="customerDataTable"
          :loading="customerTableLoading"
          :pagination="false"
          :rowKey="(record,index)=>index"
          @change="handleTableChange"
          :customRow="click"
        >
        </a-table>

      </a-modal>
    </a-modal>
  </div>

</template>

<script> 
import {getCustomerConsult} from '@/api/customer/customer'
import areaObj from '@/assets/flowable/js/areaData'
import moment from 'moment'
import { getDeptList } from '@/api/modular/main/customer/customerScene'
import { SelectCustomer, AddTgsDeptReceive, DesktopDeptList } from '@/api/modular/main/customer/cashier'

export default {
  data(){
    return{
      customer_response:'',
      value: [],
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      sex:[{'id':'0','name':'男'},{'id':'1','name':'女'}],
      CustomerConsult: { //客户咨询下拉系列
        comeHosStatus : [], //来院意向
        consultTools : [],//咨询工具
        contactDetails : [],//联系方式
      },
      //客户诉求列表
      disabled:true,
      visible: false,
      visibleTable: false,
      visiblePopover:false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      customerTableLoading:false,
      pagination: {
        current: 1,//当前页
        pageSize: 10,//当前页数
        total: 0,//总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'],//这里注意只能是字符串，不能是数字
        showTotal: total => `共有 ${ total} 条数据`,//分页中显示总的数据
      },
      customerDataTable:[],
      deptList:[],
      columns: [
        { title: '序号', customRender: (text, record, index)=>(this.pagination.current-1)*this.pagination.pageSize+(index+1), align:'center' },
        { title: '姓名', dataIndex: 'name', align:'center' },
        { title: '卡号', dataIndex: 'cardNo', align:'center' },
        { title: '开发员', dataIndex: 'developerName', customRender:developerName=>developerName?developerName:'无', align:'center' },
        { title: '咨询师', dataIndex:'consultManName', align:'center' },//如果需要整行的数据则去掉该字段customRender:consultMan=>{return consultMan?consultMan:'无'}},
        { title: '登记时间', dataIndex: 'registDate', align:'center'}
      ],
      phoneNumberReg: false,
      searchInputLoading:false
    }
  },
  created() {
    this.getCustomerConsult()
  },
  methods:{
    phoneCheck(rule,value,callbackFn){
      const reg =/^[1][3,4,5,6,7,8,9][0-9]{9}$/ 
      if(!reg.test(value)){
        callbackFn("请输入11位正确的联系方式") 
        this.phoneNumberReg = false 
        return
      }else{
        this.phoneNumberReg = true
      }
      callbackFn()
    },
    moment,
    filter(inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    },
    add (key) {
      this.visible = true
      this.confirmLoading = false
      this.disabled=true
      this.currentActiveKey = key
      console.log("key:",key)
      DesktopDeptList().then((res) => {
        this.deptList = res.data
      })
      this.$nextTick(()=>{
        this.$refs.phoneInput.focus()
        this.form.resetFields()
      })
    },
    handleSubmit(){
      console.log('点击弹出窗口确定')
    },
    /**
     表单校验手机号格式
     * */
    validatorPhone (rule, value, callback) {
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!reg.test(value)) {
        callback('11位')
      }
      callback()
    },
    /**
     表单校验年龄
     * */
    validatorAge (rule, value, callback) {
      if(!value){
        callback()
      }
      if(value>0&&value<100){
        callback()
      }
      callback('年龄必须为1-99')
    },
    /**
     下拉接口集合
     * */
    getCustomerConsult(){
      getCustomerConsult().then(res => {
        this.CustomerConsult = res
      })
    },

    /**
     判断渲染表格
     * */
    resToRender(res){
      if(res.code==200){
        //搜索不到用户
        if(res.rows.length<=0){
          const tel =this.form.getFieldValue('customerContact.contactContent')
          this.form.setFields({
            [`customerContact.contactContent`]:{
              errors:[{ message:'该客户不存在！', field: `customerContact.contactContent`}],
              value:tel
            }
          })
          this.disabled=false
        }else if(res.rows.length==1){
          //搜索到一条数据，直接渲染，需要选择点击
          this.getCustomerInfoAndRender(res.rows[0])
          
        }else{
          //搜索到用户数据两条以上
          this.visibleTable=true
          this.customerDataTable=res.rows
        }
      }
    },
    /**
     查询客户
     * */
    searchCustomer(){
      this.searchInputLoading = true
      if(!this.phoneNumberReg){
        this.searchInputLoading = false
        return false 
      }

      const tel_value =this.form.getFieldValue('customerContact.contactContent')
      const tel =tel_value?tel_value.trim():tel_value
      if(!tel){
        this.form.setFields({
          [`customerContact.contactContent`]:{
            errors:[{ message:'请填写联系号码！', field: `customerContact.contactContent`}],
          }
        })
        return
      }
      this.form.resetFields()
      this.form.setFieldsValue({
        'customerContact.contactContent':  tel,
      })
      let sendData = {
        tel: tel
      }
      console.log(sendData)
      
      SelectCustomer(sendData).then(res=>{
        this.resToRender(res)
        if(res.code == 200){
          if(res.rows.length < 1){
            this.$message.error('该客户不存在，请引导客户至客户分诊登记！')
          }
        }else{
          this.$message.error(res.msg)
        }
        this.searchInputLoading = false
        this.confirmLoading = false
      })
      
    },
    /**
     提交表单
     * */
    submit(){
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
       
        this.confirmLoading = true
        if (errors) {
          console.log('表单检验未通过111',errors,values)
          this.confirmLoading = false
          return
        }
        
        // if( values.consultRecord.orderDate){
        //   values.consultRecord.orderDate = moment(values.consultRecord.orderDate).format('YYYY-MM-DD HH:mm:ss')
        // }
        // if(values.customer.infoSource&&values.customer.infoSource?.length>0){
        //   values.customer.infoSource=values.customer.infoSource[1]
        // }else{
        //   values.customer.infoSource=this.customer_response.info_source
        // }
         
        // if( values.customer.areaId instanceof Array ){
        //   const len = values.customer.areaId.length
        //   values.customer.areaId=values.customer.areaId[len-1]
        // }else if(typeof (values.customer.areaId) == 'undefined'){
        //   values.customer.areaId = null
        // } else{
        //   values.customer.areaId=this.customer_response.area_id
        // }
        // if(values.customer.sex){
        //   if(values.customer.sex==='男'){
        //     values.customer.sex=0
        //   }
        //   if(values.customer.sex==='女'){
        //     values.customer.sex=1
        //   }
        // }
        // if(this.customer_response){
        //   values.customer.customerId=this.customer_response.customerId
        // }
        console.log(this.customer_response)
        let d = this.customer_response
         console.log(values)
        let sendData = {
          clientId: d.tbCustomerId,
          receiveManId: d.consultManId,
          receiveMan: d.consultManName,
          deptId: values.execDept,
          remark: '',
          contactList:[{
            clientId: d.tbCustomerId,
            remark: '',
            contactType: values.customerContact.contactType,
            contactContent: ''
          }],
          admissionState: this.currentActiveKey == '2' ? '09011304' : '09011301'

        // this.currentActiveKey
        }
        AddTgsDeptReceive(sendData).then(res => {
          if(res.code == 200){
            this.$message.success(res.message)
            this.visible=false
            this.confirmLoading = false
            this.$emit('addOk')
          }else{
            this.$message.error(res.message)
            this.confirmLoading = false
          }
        })
        // addNetConsultation(values).then(res =>{
        //   if(res.code==200){
        //     this.$message.success({
        //       content:'增加成功',
        //       duration:1,
        //       onClose:()=>{
        //         this.visible=false
        //         // this.$parent.getList()
        //         this.$parent.$refs.customerNetList.refresh()
        //         this.confirmLoading = false
        //       }
        //     })
        //   }else{
        //     this.$message.info({
        //       content:res.message,
        //       duration:1,
        //       onClose:()=>{
        //         this.confirmLoading = false
        //       }
        //     })
        //   }

        // })
      })
    },
    /**
     分页动作监听
     * */
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.queryParam.pageNum = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      this.getList()
    },
    /**
     表格行点击事件
     * */
    click(record, index){
      return {
        on: {
          dblclick:()=>{ 
            this.getCustomerInfoAndRender(record)
          }
        }
      }
    },
    handleCancel () {
      this.form.setFields({
        [`customerContact.contactContent`]:{
          value:null
        }
      })
      this.form.resetFields()
      this.visible = false
    },
    /**
     请求用户资料数据并且渲染页面
     * */
    getCustomerInfoAndRender(params){ 
      this.customer_response= params
      this.form.setFieldsValue({

        'customer.age': params.age,
        'customer.name': params.name,
        'customer.cardNo': params.card_no,
        'customer.sex':params.sex==1?'女':'男',
        'customerContact.contactType':params.contact_type,
        // 'customerContact.contactContent':params.contact_content,
      })
      this.visibleTable=false
      if(!params.age||params.age<0||params.age>99){
        this.disabled_age=false
      }
      
      
      // getCustomerInfo(params).then(res=>{
      //   console.log('客户信息',res)
      //   if(res.code==200){
      //     const customerInfo = res.data
      //     this.customer_response=res.data
      //     this.form.setFieldsValue({
      //       'customer.age': customerInfo.age,
      //       'customer.name': customerInfo.name,
      //       'customer.cardNo': customerInfo.card_no,
      //       'customer.sex':customerInfo.sex==1?'女':'男',
      //       'customerContact.contactType':customerInfo.contact_type,
      //       'customerContact.contactContent':customerInfo.contact_content,
      //     })
      //     this.visibleTable=false
      //     if(!customerInfo.age||customerInfo.age<0||customerInfo.age>99){
      //       this.disabled_age=false
      //     }
      //   }else{
      //     this.$message.info({
      //       content:res.message,
      //       duration:1,
      //       onClose:()=>{
      //         this.visibleTable=false
      //       }
      //     })
      //   }
      // })
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-head-title{
  font-weight: bold;
}
/deep/ .ant-page-header-heading-title{
  font-weight: normal;
  font-size: 16px;
}
/deep/ .ant-card-body {
  padding: 24px 12px 0;
}
/deep/ .ant-form-item-control-wrapper{
  width: 100%;
}

</style>